import React from 'react';
import { connect } from 'dva';
import { Picker,Drawer, List, NavBar,Icon, InputItem , TabBar,DatePicker ,Toast ,Button,TextareaItem,WhiteSpace,Card,WingBlank} from 'antd-mobile';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail} from '../../utils/Validator.js'
import options from '../../models/CityData.js'
import PropTypes from 'prop-types';
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import {reqwest_get,reqwest_post} from '../../utils/Reqwest.js';
import G2 from 'g2';
import createG2 from 'g2-react';
import GM from 'g2-mobile';
// import createG2 from 'g2-react';
GM.Global.pixelRatio = 2;
var Util = GM.Util;
const YChart = createG2(chart => {
  // 以 year 为维度划分分面
  var Stat = G2.Stat;
  chart.coord('theta', {
    radius: 0.8 // 设置饼图的大小
  });
  chart.legend('name', {
    position: 'bottom',dx: 10,
    itemWrap: true,
    word:{
      fontSize:40
    },
    formatter: function(val) {
      return val
    }
  });
  // chart.axis()
  chart.tooltip({
    title: null,
    map: {
      value: 'value'
    }
  });
  chart.intervalStack()
    .position(Stat.summary.percent('value'))
    .color('name')
    .label('name*..percent',{
      label:{
        fontSize:40
      },
      renderer:function(name, percent,index){
        // let _pre = null;
        // console.log(percent)
        // percent = (percent * 100).toFixed(2) + '%';
        // if(index<_aa.length){
        //   _pre = _aa[index].value;
        // }
      return name + ' ' + Math.floor(percent.point.value)+"%";
    }});
  chart.render(); 
});
class Home extends React.Component{
		constructor(props){
		super(props);
		this.state={
      data:[],
			reginos:[],
			disable:true,
      wallet:undefined,
      ydata: [
        {name:'提成', value: 100},
        {name:'返利', value: 0},
      ]
      // companies:sessionStorage['companies']===undefined||'undefined'?[]:JSON.parse(sessionStorage['companies']),
      // material:sessionStorage['material']===undefined||'undefined'?[]:JSON.parse(sessionStorage['material']),
      // store_tree:sessionStorage['store_tree']===undefined||'undefined'?[]:JSON.parse(sessionStorage['store_tree']),
		}
	}
  getServer(){
    let _this = this;
    // debugger;
    // this.setState({loading:true});
    let _profit1,_profit2,_profit3;
    let timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
    let Tomorrow = timeStamp + 86400 * 1;
    console.log(Tomorrow)
    // if(window.localStorage['date_source']==undefined||(window.localStorage['date_source']*1 + 86400 * 1)<=timeStamp){
      reqwest_get('/api/users/statistics',{
          access_token:localStorage['token'],
        },(data)=>{
          this.setState({data:data.order})
          window.localStorage['date_table']=JSON.stringify(data.order)
          window.localStorage['date_source']=timeStamp;
        })
    // }
    reqwest_get('/api/wallets/me',{
        access_token:localStorage['token'],
      },(data)=>{
        this.setState({wallet:data.wallet})
        if(data.status=='success'){
          _this.setState({wallet:data.wallet});
          if(data.wallet.amount!=0&&data.wallet.income!=0){
            _profit1=data.wallet.expend/data.wallet.amount*100;
            _profit2=data.wallet.income/data.wallet.amount*100;
            _this.setState({ydata:[
              {year:2017, name:'提成', value: _profit1},
              {year:2017, name:'返利', value: _profit2},
            ]})
          }
        }else{
          Toast.fail(data.msg,0.4)
        }
      })
  }

	componentWillMount(){
    this.getServer()
	}
  componentDidMount(){
     // var  data = [
     //    {a:'1',d: 'saber', b: 3000, c: '1'},
     //    {a:'1',d: 'lancel', b: 1000, c: '2'},
     //    {a:'1',d: 'rider', b: 2000, c: '3'}
     //  ];
      let _data = [
        {"time": '2017-07-01',"tem": 10},
        {"time": '2017-07-02',"tem": 22},
        {"time": '2017-07-03',"tem": 20},
        {"time": '2017-07-04',"tem": 26},
        {"time": '2017-07-05',"tem": 20},
        {"time": '2017-07-06',"tem": 26},
        {"time": '2017-07-07',"tem": 27},
      ];
      console.log(this.state.data)
      let chart = new GM.Chart({
        id: 'c2'
      });
      // let defs = {
      //   time: {
      //     type: 'timeCat',
      //     mask: 'mm-dd',
      //     tickCount: 2,
      //     range:[0,1]
      //   },
      //   tem: {
      //     tickCount: 10,
      //     min: 0,
      //     // tickInterval: 10
      //   }
      // };
      // //配置time刻度文字样式
      // let label = {
      //   fill: '#979797',
      //   font: '0.2rem san-serif',
      //   offset:1
      //   // fontSize:'1rem',
      //   // labelOffset:
      // };
      // chart.source(data,{
      //   type:'cat',
      //   tickCount:5,
      //   min:0,

      // });
      // chart.coord('polar', {
      //   transposed: true,
      // });
      // // chart.legend('d', {
      // //   position: 'bottom',
      // //   itemWrap: true,
      // //   formatter: function(val) {
      // //         return val + ': ' + obj.value + '%'; 
      // //   }
      // // });
      // chart.axis('b',{
      //   label: function(text, index, total) {
      //     var cfg = {
      //       fill: '#979797',
      //       font: '0.28rem san-serif',
      //     };
      //     if(index<data.length){
      //       console.log(data[index].b)
      //       cfg.text = data[index].b;
      //       cfg.offset=data[index].b;
      //     }
           
      //     return cfg;
      //   },
      //   line:{
      //     lineWidth:1,stroke:'#ccc'
      //   },
      //   labelOffset: 30, 
      //   tickLine: {
      //     lineWidth: 1,
      //   }
      // });
      // chart.intervalStack().position('a*b').color( 'c');
      // // chart.line().position('a*b').shape('smooth');
      // // chart.intervalStack().position('a*b').color( 'c',['red', 'blue','#391623']);
      // chart.animate().wavec();
      // chart.render();
      // 配置刻度文字大小，供PC端显示用(移动端可以使用默认值20px)
       var defs = {
        time: {
          type: 'timeCat',
          mask: 'mm-dd',
          tickCount: 7,
          range:[0,1]
        },
        tem: {
          tickCount: 10,
          min: 0
        }
      };
      //配置time刻度文字样式
      var label = {
        fill: '#979797',
        font: '24px san-serif',
        offset: 6
      };
      chart.axis('time', {
        label: function (text, index, total) {
          var cfg = Util.mix({}, label);
          // 第一个点左对齐，最后一个点右对齐，其余居中，只有一个点时左对齐
          if (index === 0) {
            cfg.textAlign = 'start';
          }
          if (index > 0 && index === total - 1) {
            cfg.textAlign = 'end';
          }
          return cfg;
        }
      });
      //配置刻度文字大小，供PC端显示用(移动端可以使用默认值20px)
      chart.axis('tem', {
        label: label
      });
      chart.source(this.state.data, defs);
      chart.line().position('month*temperature').shape('smooth');
      chart.point().position('month*temperature');
      chart.render();
  }
	render(){
		console.log(this.state.list);
    const _color=['red', 'blue','#391623'];
		const _this =this;
    const _companies =[];
    const _material=[];
    const {wallet,list} = this.state;
		return(
			<div className={`${style.layout}`}>
				<List className={`${Reset.tel_list_header}`} renderHeader={() => '首页'}>
          <WhiteSpace size="xl" />
            <List.Item className={`${Reset.tel_list}`}>
              我的钱包：￥{wallet.amount}
              &ensp;&ensp;&ensp;
              收入：￥{wallet.expend}
            </List.Item>
          <WhiteSpace size="xl" />
          </List>
          <WhiteSpace size="xl" />
          <List className={`${Reset.tel_list_header}`}>
          <div className={`${style.tel_chart}`} style={{padding:'0.4rem 0.4rem 0.4rem 0',}} >
            <ul style={{paddingLeft:'0.4rem'}}>
              <li>平均业绩</li>
            </ul>
            <canvas id="c2" style={{width:'90vw',height:'5rem',marginLeft:'0.4rem'}}></canvas>
          </div>
          </List>
          <WhiteSpace size="xl" />
          <List className={`${Reset.tel_list_header}`}>
          <div className={`${style.tel_chart}`}>
            <ul style={{padding:'0.4rem'}}>
              <li>收入</li>
            </ul>
            <YChart
                data={this.state.ydata}
                width={600}
                height={600}
                forceFit={true}
                ref="myChart"
              />
          </div>
            
          </List>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}     
export default connect()(Home)
